import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    
    const status = exception instanceof HttpException
      ? exception.getStatus()
      : HttpStatus.INTERNAL_SERVER_ERROR;
      
    const message = exception.message || '服务器内部错误';
    const errorResponse = exception.getResponse();
    
    // 获取更详细的错误信息，如验证错误
    let errors: string[] | null = null;
    if (typeof errorResponse === 'object' && errorResponse !== null) {
      const errorObj = errorResponse as Record<string, any>;
      if (errorObj.message && Array.isArray(errorObj.message)) {
        errors = errorObj.message;
      }
    }
    
    const responseBody = {
      success: false,
      code: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      message,
      errors,
    };
    
    this.logger.error(
      `${request.method} ${request.url} ${status} - ${message}`,
      errors ? errors.join(', ') : undefined,
    );
    
    response.status(status).json(responseBody);
  }
} 